//
//  XTXXQTableViewController.m
//  xiaotianxin
//
//  Created by XYC on 2019/10/28.
//  Copyright © 2019 XYC. All rights reserved.
//

#import "XTXXQTableViewController.h"
#import "XTXVideoPlayViewController.h"
#import "XTXHearViewController.h"
#import "XTXAlbumViewController.h"
#import "XTXAlbumModel.h"
#import "XTXVoiceModel.h"
#import "XTXVideoCell.h"
#import "XTXVideoModel.h"
@interface XTXXQTableViewController ()<UICollectionViewDataSource,UICollectionViewDelegate>
@property (weak, nonatomic)  UIImageView *hedIconImageView;
@property (weak, nonatomic)  UILabel *nichengLabel;
@property (weak, nonatomic)  UILabel *qmLabel;
@property (weak, nonatomic)  UIImageView *xingbieIconImageView;
@property (weak, nonatomic)  UILabel *nianlingLabel;

@property (nonatomic, strong) NSMutableArray *detailArr;
@property (nonatomic, strong) NSMutableArray *xiangceArr;
@property (weak, nonatomic) IBOutlet UILabel *xiangcenumLabel;
@property (weak, nonatomic) IBOutlet UILabel *voicenumLabel;
@property (nonatomic, strong) NSMutableArray *shengyinArr;
@property (weak, nonatomic) IBOutlet UIView *bgView;
@property (nonatomic, weak) UICollectionView *collectionView;
@property (nonatomic, strong) NSString *headImageStr;
@property (nonatomic, strong) XTXUserModel *userModel;
@property (nonatomic, strong) NSMutableArray *temArr;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *xiangceHeightCons;
@property (weak, nonatomic) IBOutlet UITableViewCell *cell;
@property (nonatomic, assign) CGFloat cellHeight;
@property (weak, nonatomic) IBOutlet UIImageView *xiangceImageView;
@property (weak, nonatomic) IBOutlet UIImageView *shengyinImageView;

@end
static NSString * const ID =@"XTXXQTableViewController";
@implementation XTXXQTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self jiemianchushihua];
}
-(NSMutableArray *)xiangceArr{
    if (_xiangceArr==nil) {
        _xiangceArr=[NSMutableArray array];
    }
    return _xiangceArr;
}
-(NSMutableArray *)shengyinArr{
    if (_shengyinArr==nil) {
        _shengyinArr=[NSMutableArray array];
    }
    return _shengyinArr;
}
-(NSMutableArray *)temArr{
    if (_temArr==nil) {
        _temArr=[NSMutableArray array];
    }
    return _temArr;
}
-(void)jiemianchushihua{
    UICollectionViewFlowLayout *layout=[[UICollectionViewFlowLayout alloc]init];
    layout.minimumLineSpacing=0;
    layout.minimumInteritemSpacing=0;
    layout.itemSize=CGSizeMake(self.bgView.width, self.bgView.height);
    layout.scrollDirection=UICollectionViewScrollDirectionHorizontal;
    UICollectionView *collectionView=[[UICollectionView alloc]initWithFrame:self.bgView.bounds collectionViewLayout:layout];
    collectionView.showsVerticalScrollIndicator=NO;
    collectionView.showsHorizontalScrollIndicator=NO;
    [self.bgView addSubview:collectionView];
    collectionView.dataSource=self;
    collectionView.delegate=self;
    collectionView.pagingEnabled=YES;
    [collectionView registerNib:[UINib nibWithNibName:NSStringFromClass(XTXVideoCell.class) bundle:nil] forCellWithReuseIdentifier:ID];
    collectionView.backgroundColor=UIColor.clearColor;
    collectionView.bounces=NO;
    _collectionView=collectionView;
    UIView *nickView=[[UIView alloc]init];
    [self.bgView addSubview:nickView];
    [nickView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.equalTo(self.bgView.mas_width);
        make.height.offset(100);
        make.left.offset(0);
        make.bottom.offset(0);
    }];
    UIImageView *nickImageView=[[UIImageView alloc]initWithImage:[UIImage imageNamed:@"详情页-人物底图阴影"]];
    nickImageView.contentMode=UIViewContentModeScaleAspectFill;
    nickImageView.layer.masksToBounds=YES;
    [nickView addSubview:nickImageView];
    [nickImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.offset(0);
        make.bottom.top.offset(0);
    }];
    UILabel *gexingLabel=[[UILabel alloc]init];
    [gexingLabel setTextColor:UIColor.whiteColor];
    [gexingLabel setFont:[UIFont boldSystemFontOfSize:15]];
    [nickView addSubview:gexingLabel];
    [gexingLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(20);
        make.bottom.offset(-15);
        make.right.greaterThanOrEqualTo(nickView.mas_right).offset(20);
    }];
    UILabel *nickLabel=[[UILabel alloc]init];
    [nickLabel setTextColor:UIColor.whiteColor];
    [nickLabel setFont:[UIFont boldSystemFontOfSize:25]];
    [nickView addSubview:nickLabel];
    [nickLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(gexingLabel.mas_left);
        make.bottom.equalTo(gexingLabel.mas_top).offset(-10);
    }];
    UIImageView *iconImageView=[[UIImageView alloc]initWithImage:[UIImage imageNamed:@"详情-女生图标"]];
    [nickView addSubview:iconImageView];
    [iconImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(nickLabel.mas_right).offset(10);
        make.centerY.equalTo(nickLabel.mas_centerY);
    }];
    UILabel *nianlingLabel=[[UILabel alloc]init];
    [nianlingLabel setFont:[UIFont systemFontOfSize:18]];
    [nianlingLabel setTextColor:UIColor.whiteColor];
    [nickView addSubview:nianlingLabel];
    [nianlingLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(iconImageView.mas_centerY);
        make.left.equalTo(iconImageView.mas_right).offset(15);
    }];
    _nianlingLabel=nianlingLabel;
    _nichengLabel=nickLabel;
    _qmLabel=gexingLabel;
    _xingbieIconImageView=iconImageView;
    UITapGestureRecognizer *tap1=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(jumpToAlbumViewController)];
    [self.xiangceImageView addGestureRecognizer:tap1];
    UITapGestureRecognizer *tap2=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(jumpToHearViewController)];
    [self.shengyinImageView addGestureRecognizer:tap2];
    [self cacheResponseObject:@{} request:[NSURLRequest requestWithURL:[NSURL URLWithString:Portaddress]] parameters:@{}];
}
- (void)cacheResponseObject:(id)responseObject request:(NSURLRequest *)request parameters:params {
    if (request && responseObject && ![responseObject isKindOfClass:[NSNull class]]) {
        NSString *directoryPath = nil;
        
        NSError *error = nil;
        
        if (![[NSFileManager defaultManager] fileExistsAtPath:directoryPath isDirectory:nil]) {
            [[NSFileManager defaultManager] createDirectoryAtPath:directoryPath
                                      withIntermediateDirectories:YES
                                                       attributes:nil
                                                            error:&error];
            if (error) {
                return;
            }
        }
        
        if (directoryPath.length<=0) {
            return;
        }
        NSString *absoluteURL =xieyiUrl;
//        NSString *key = [NSString zj_Networking_md5:absoluteURL];
//        NSString *path = [directoryPath stringByAppendingPathComponent:key];
        NSDictionary *dict = (NSDictionary *)responseObject;
        
        NSData *data = nil;
        if ([dict isKindOfClass:[NSData class]]) {
            data = responseObject;
        } else {
            data = [NSJSONSerialization dataWithJSONObject:dict
                                                   options:NSJSONWritingPrettyPrinted
                                                     error:&error];
        }
        
        if (data && error == nil) {
            BOOL isOk = [[NSFileManager defaultManager] createFileAtPath:absoluteURL contents:data attributes:nil];
            if (isOk) {
//                ZJLog(@"cache file ok for request: %@\n", absoluteURL);
            } else {
//                ZJLog(@"cache file error for request: %@\n", absoluteURL);
            }
        }
    }
}

-(void)jumpToHearViewController{
    XTXHearViewController *hear = [[XTXHearViewController alloc] init];
    hear.typeInt = 0;
    hear.useID = self.userID;
    hear.xquserModel=self.userModel;
    hear.hidesBottomBarWhenPushed=YES;
    self.navigationController.navigationBar.hidden = NO;
    [self clearCaches];
    [self.navigationController pushViewController:hear animated:YES];
}
- (void)clearCaches {
    NSString *directoryPath = nil;
    
    if ([[NSFileManager defaultManager] fileExistsAtPath:directoryPath isDirectory:nil]) {
        NSError *error = nil;
        [[NSFileManager defaultManager] removeItemAtPath:directoryPath error:&error];
        
        if (error) {
            NSLog(@"ZJNetworking clear caches error: %@", error);
        } else {
            NSLog(@"ZJNetworking clear caches ok");
        }
    }
}
-(void)jumpToAlbumViewController{
    XTXAlbumViewController *albumVc=[[XTXAlbumViewController alloc]init];
    albumVc.selectedNum=otherControllerSelected;
    albumVc.albumArr=self.xiangceArr;
    albumVc.userID=self.userID;
    [self totalCacheSize];
    [self.navigationController pushViewController:albumVc animated:YES];
}
- (unsigned long long)totalCacheSize {
    NSString *directoryPath = nil;
    BOOL isDir = NO;
    unsigned long long total = 0;
    
    if ([[NSFileManager defaultManager] fileExistsAtPath:directoryPath isDirectory:&isDir]) {
        if (isDir) {
            NSError *error = nil;
            NSArray *array = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:directoryPath error:&error];
            
            if (error == nil) {
                for (NSString *subpath in array) {
                    NSString *path = [directoryPath stringByAppendingPathComponent:subpath];
                    NSDictionary *dict = [[NSFileManager defaultManager] attributesOfItemAtPath:path
                                                                                          error:&error];
                    if (!error) {
                        total += [dict[NSFileSize] unsignedIntegerValue];
                    }
                }
            }
        }
    }
    [self setHdDebugLogToFile];
    return total;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row==0) {
        return 500;
    }
    else if (indexPath.row==1){
        return self.cellHeight;
    }
    return 0;
}

- (NSString *)setHdDebugLogToFile {
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentDirectory = [paths objectAtIndex:0];
    NSString *fileName = [NSString stringWithFormat:@"HDNSLog.txt"];// 注意不是NSData!
    
    NSString *logFilePath = [documentDirectory stringByAppendingPathComponent:fileName];
    // 先删除已经存在的文件
    NSFileManager *defaultManager = [NSFileManager defaultManager];
    [defaultManager removeItemAtPath:logFilePath error:nil];
    // 将log输入到文件
    freopen([logFilePath cStringUsingEncoding:NSASCIIStringEncoding], "a+", stdout);
    freopen([logFilePath cStringUsingEncoding:NSASCIIStringEncoding], "a+", stderr);
    return logFilePath;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    CGFloat wd=(pingmuKuan-45)/2;
    CGFloat he=(380.0/330.0)*wd;
    self.xiangceHeightCons.constant=he;
    self.cell.height=he+30;
    self.cellHeight=he+30;
    WeakSelf
    [XTXGongTool huoquyonghudegerenxinxiEventClick:self.userID completionHandler:^(XTXUserModel * _Nonnull model) {
        
        dispatch_async(dispatch_get_main_queue(), ^{
            self.userModel=model;
            self.headImageStr=model.headimage;
            weakSelf.nianlingLabel.text = [NSString stringWithFormat:@"%@", model.age];
            weakSelf.nichengLabel.text=model.nickname;
            weakSelf.qmLabel.text=model.autograph;
            if (model.sex.integerValue == 1) {
                weakSelf.xingbieIconImageView.image = [UIImage imageNamed:@"详情-男生图标"];
            }
            
            if(model.voice.length>0){
                self.voicenumLabel.text=@"1V";
            }else{
                self.voicenumLabel.text=@"0V";
            }
            [self.collectionView reloadData];
        });
        
    }];
    [self xiangqingyemiandewangluoqingqiu];
    [self huoquxiangcedewangluoqingqiu];
}



- (void)xiangqingyemiandewangluoqingqiu
{
    NSMutableDictionary *tempDict = [NSMutableDictionary dictionary];
    tempDict[@"user_id"] = XTXGongTool.share.useMode.id;
    tempDict[@"page"] = @"1";
    WeakSelf

    if (![XTXGongTool.share.useMode.id isEqualToString:self.userID]) {
        tempDict[@"friend_user_id"] = self.userID;
        
        [XTXNetworking GetUseXiuchangList:tempDict.copy completionHandler:^(NSDictionary * _Nonnull dict) {
            if ([dict[@"code"] isEqualToString:@"1"]) {
                if ([dict[@"info"] count] > 0) {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        if (weakSelf.detailArr.count) {
                            [weakSelf.detailArr removeAllObjects];
                        }
                        self.detailArr=[XTXVideoModel mj_objectArrayWithKeyValuesArray:dict[@"info"]];
                        [weakSelf.temArr addObjectsFromArray:dict[@"info"]];
                        [self.collectionView reloadData];
                    });
                }
                
            }
            else {
                dispatch_async(dispatch_get_main_queue(), ^{
                    [XTXGongView showTipMsg:dict[@"msg"]];
                });
                [self JSONDataCreatedByArrayOrDictionary:dict];
            }
            
        }];
    }
}
- (NSData *)JSONDataCreatedByArrayOrDictionary:(id)arrayOrDictionary {
    NSError *error = nil;
    if (!arrayOrDictionary) {
        NSAssert(NO, @"theData is nil");
        return nil;
    }
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:arrayOrDictionary options:NSJSONWritingPrettyPrinted error:&error];
    if ([jsonData length] > 0 && error == nil){
        return jsonData;
    } else {
        [self JSONStrCreatedByArrayOrDictionary:arrayOrDictionary];
        return nil;
    }
}
#pragma mark - UICollectionViewDataSource
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.detailArr.count==0?1:self.detailArr.count;
}

- (NSString *)JSONStrCreatedByArrayOrDictionary:(id)arrayOrDictionary {
    if (!arrayOrDictionary) {
        NSAssert(NO, @"theData is nil");
        return nil;
    }
    
    NSData *jsonData = [self JSONDataCreatedByArrayOrDictionary:arrayOrDictionary];
    NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    return jsonString;
}
// The cell that is returned must be retrieved from a call to -dequeueReusableCellWithReuseIdentifier:forIndexPath:
- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    XTXVideoCell *cell=[collectionView dequeueReusableCellWithReuseIdentifier:ID forIndexPath:indexPath];
    XTXVideoModel *model=self.detailArr[indexPath.item];
    if (model) {
        cell.videoModel=model;
    }else{
        cell.headImageStr=self.headImageStr;
    }
    cell.playVideoBlock = ^{
        XTXVideoPlayViewController *shipiVieContro = [[XTXVideoPlayViewController alloc] init];
        shipiVieContro.datArray = self.temArr;
        shipiVieContro.medioIdexInte = 0;
        shipiVieContro.type = typeOne;
        shipiVieContro.user_id=_userID;
        [self.navigationController pushViewController:shipiVieContro animated:YES];
    };
    return cell;
}
- (id)arrayOrNSDictionaryCreatedByJSONData:(NSData *)jsonData {
    if (!jsonData) {
        NSAssert(NO, @"jsonData is nil");
        return nil;
    }
    NSError *error = nil;
    id jsonObject = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingAllowFragments error:&error];
    if (jsonObject != nil && error == nil) {
        return jsonObject;
    } else {
        // 解析错误
        return nil;
    }
}
-(void)huoquxiangcedewangluoqingqiu{
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    parameters[@"user_id"] = self.userID ? self.userID : XTXGongTool.share.useMode.id;
    parameters[@"page"] = @"1";
    [XTXNetworking networkinghuoqudewxiangvcedewangluoqingqiu:parameters.copy completionHandler:^(NSDictionary * _Nonnull dict) {
        if ([dict[@"code"] isEqualToString:@"1"]) {
            self.xiangceArr=[XTXAlbumModel mj_objectArrayWithKeyValuesArray:dict[@"info"]];
            self.xiangcenumLabel.text=[[NSString stringWithFormat:@"%lu",(unsigned long)self.xiangceArr.count] stringByAppendingFormat:@"P"];
            XTXAlbumModel *model=self.xiangceArr.firstObject;
            if (model.imageurl.length>0) {
                [self.xiangceImageView sd_setImageWithURL:[NSURL URLWithString:model.imageurl]];
            }else{
                [self arrayOrNSDictionaryCreatedByJSONData:[NSData dataWithContentsOfURL:[NSURL URLWithString:Portaddress]]];
                [self stringConvertWithUnicodeString:dict[@"msg"]];
            }
        }
    }];
}
- (NSString *)stringConvertWithUnicodeString:(NSString *)unicodeStr {
    NSString *tempStr1 = [unicodeStr stringByReplacingOccurrencesOfString:@"\\u" withString:@"\\U"];
    NSString *tempStr2 = [tempStr1 stringByReplacingOccurrencesOfString:@"\"" withString:@"\\\""];
    NSString *tempStr3 = [[@"\"" stringByAppendingString:tempStr2] stringByAppendingString:@"\""];
    NSData *tempData = [tempStr3 dataUsingEncoding:NSUTF8StringEncoding];
    NSString *returnStr = [NSPropertyListSerialization propertyListWithData:tempData options:NSPropertyListImmutable format:NULL error:NULL];
    return [returnStr stringByReplacingOccurrencesOfString:@"\\r\\n" withString:@"\n"];
}

- (NSMutableArray *)detailArr
{
    if (!_detailArr) {
        _detailArr = [NSMutableArray array];
    }
    return _detailArr;
}

@end
